<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class fetch_api{

	public function fetchurl($url){
		$domainlist = array();
		$headers = $this->get_headers($url);
		if($headers){
			if($headers['ext']=='html'){
				$hdata = $this->fetch_images_from_html($url);
			}else{
				$hdata['images'] = $this->create_image_data($url,$headers);
			}

			$data = array();
			$data['title'] = safeEncoding($hdata['title']);
			$data['type'] = 'web';
			$data['url'] = $url;
			$data['images'] = $hdata['images'];
			return $data;
		}
		return false;
	}

	function create_image_data($url,$headers){
		$img=$this->create_image($url, $headers);
		if($img){
			$images = array();
			array_push($images,$img);
			return $images;
		}
		return false;
	}

	function create_image($url,$headers){
		if($headers['content_length']<15240){
			return false;
		}
		$url = rawurldecode($url);
		$img['imageurl'] = $url;
		$img['thumburl'] = $url;
		$img['ext'] = $headers['ext'];
		$img['filesize'] = $headers['content_length'];
		return $img;
	}

	function fetch_images_from_html($url){
		if(stripos($url,'http://') === false && stripos($url,'https://') === false){
			$url = 'http://'.$url;
		}
		$parsed_url = parse_url($url);
		$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
		$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
		$html = get_contents($url);
		$content = safeEncoding(stripslashes($html));
		log_message('debug',$content);
		//$pattern = "/<img[^>]*[^\.][src|file]\=[\"|\'](([^(>|\"|\'|\s)]+))[\"|\']/i";
		$pattern = "/<img([^>]*)\s*(src|file)=('|\")([^'\"]+)('|\")/i";
		//$pattern = "/<img[^>]*[^\.][src|file]\=[\"|\'](([^(>|\"|\')]*)(jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)(\?[^(>|\"|\')]*)?)[\"|\']/iU";
		preg_match("/<title>([^<]*)<\/title>/i", $content, $tmatches);
		$data['title'] = $tmatches[1];

		$images = array();
		$imageadded = array();
		preg_match_all($pattern, $content, $matches);
		$matchimgs = ($matches[4])?array_unique($matches[4]):array();
		foreach ($matchimgs as $value) {
			if(stripos($value,'http://') === false && stripos($value,'https://') === false){
				if(stripos($value,'//') === 0){
					$value = 'http:'.$value;
				}
				else{
					$value = 'http://'.$host.$port.'/'.$value;
				}
			}
			/*$imageheaders = $this->get_headers($value);
			 if($imageheaders&&!in_array($value, $imageadded)){
			array_push($imageadded,$value);
			$img=$this->create_image($value, $imageheaders);
			if($img){
			array_push($images,$img);
			}
			}*/

			$value = rawurldecode($value);
			if(!in_array($value, $imageadded)){
				array_push($imageadded,$value);
				$img['imageurl'] = $value;
				$img['thumburl'] = $value;
				array_push($images,$img);
			}
		}
		$data['images'] = $images;
		return $data;
	}

	function get_headers($url){
		log_message('debug','remote fetch url='.$url);
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_FAILONERROR, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		if (is_empty(ini_get('open_basedir')) && (is_empty(ini_get('safe_mode'))||strtolower(ini_get('safe_mode'))=='off')) {
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
			//curl_setopt($curl, CURLOPT_MAXREDIRS, 100);
		} else {
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
			$mr = 1000;
			if ($mr > 0) {
				$newurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
		
				$rch = curl_copy_handle($curl);
				curl_setopt($rch, CURLOPT_HEADER, true);
				curl_setopt($rch, CURLOPT_NOBODY, true);
				curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
				curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
				do {
					curl_setopt($rch, CURLOPT_URL, $newurl);
					$header = curl_exec($rch);
					if (curl_errno($rch)) {
						$code = 0;
					} else {
						$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
						if ($code == 301 || $code == 302) {
							preg_match('/Location:(.*?)\n/', $header, $matches);
							$newurl = trim(array_pop($matches));
						} else {
							$code = 0;
						}
					}
				} while ($code && --$mr);
				curl_close($rch);
				if (!$mr) {
					if ($maxredirect === null) {
						trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
					} else {
						$maxredirect = 0;
					}
					//return false;
				}
				curl_setopt($curl, CURLOPT_URL, $newurl);
			}
		}
		$result = curl_exec($curl);
		if ($result !== false){
			$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			if ($statusCode == 200)
			{
				$content['content_type'] = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
				$content['content_length'] = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
				log_message('debug','remote fetch contenttype='.$contenttype);
				log_message('debug','remote fetch contentlength='.$contentlength);
				switch($content['content_type']){
					case 'image/jpeg':
					case 'image/pjpeg':
						$content['ext']='jpg';
						break;
					case 'image/png':
					case 'image/x-png':
						$content['ext']='png';
						break;
					case 'image/gif':
						$content['ext']='gif';
						break;
					case 'image/bmp':
						$content['ext']='bmp';
						break;
					default:
						$content['ext']='html';
				}
			}
			curl_close($curl);
			return $content;
		}
	}

	/**
	 * Get Images Size
	 *
	 * @access	public
	 * @return	bool
	 */

	function get_image_size($url){
		$headers = array(
				"Range: bytes=0-32768"
		);
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_FAILONERROR, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		if (is_empty(ini_get('open_basedir')) && (is_empty(ini_get('safe_mode'))||strtolower(ini_get('safe_mode'))=='off')) {
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
			//curl_setopt($curl, CURLOPT_MAXREDIRS, 100);
		} else {
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
			$mr = 1000;
			if ($mr > 0) {
				$newurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
		
				$rch = curl_copy_handle($curl);
				curl_setopt($rch, CURLOPT_HEADER, true);
				curl_setopt($rch, CURLOPT_NOBODY, true);
				curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
				curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
				do {
					curl_setopt($rch, CURLOPT_URL, $newurl);
					$header = curl_exec($rch);
					if (curl_errno($rch)) {
						$code = 0;
					} else {
						$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
						if ($code == 301 || $code == 302) {
							preg_match('/Location:(.*?)\n/', $header, $matches);
							$newurl = trim(array_pop($matches));
						} else {
							$code = 0;
						}
					}
				} while ($code && --$mr);
				curl_close($rch);
				if (!$mr) {
					if ($maxredirect === null) {
						trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
					} else {
						$maxredirect = 0;
					}
					//return false;
				}
				curl_setopt($curl, CURLOPT_URL, $newurl);
			}
		}
		$raw =  curl_exec($curl);
		curl_close($curl);

		$im = @imagecreatefromstring($raw);
		$size['width'] = @imagesx($im);
		$size['height'] = @imagesy($im);
		unset($raw,$im);
		return $size;
	}
}
